package com.zhongxi.guoyuan.view.user.gift;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.gift.GiftActivity;
import com.zhongxi.guoyuan.entity.gift.GiftOrder;
import com.zhongxi.guoyuan.entity.gift.GiftToPay;
import com.zhongxi.guoyuan.entity.gift.GroupInfo;
import com.zhongxi.guoyuan.entity.gift.RefInfo;
import com.zhongxi.guoyuan.entity.gift.StoreInfo;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.user.GiftResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.GlideCircleTransform;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.weixin.MD5;
import com.zhongxi.guoyuan.weixin.Util;
import com.zhongxi.guoyuan.zhifubao.PayResult;
import com.zhongxi.guoyuan.zhifubao.SignUtils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/4/23.
 */

public class JoinGroupActivity extends BaseActivity {
    private static final int MESSAGE_WHAT = 23;
    @Bind(R.id.ivBack)
    ImageView mIvBack;
    @Bind(R.id.tvTitle)
    TextView mTvTitle;
    @Bind(R.id.iv_head)
    ImageView mIvHead;
    @Bind(R.id.iv_group1)
    ImageView mIvGroup1;
    @Bind(R.id.iv_group2)
    ImageView mIvGroup2;
    @Bind(R.id.ll_imges)
    LinearLayout mLlImges;
    @Bind(R.id.tv_time_count_desc)
    TextView mTvTimeCountDesc;
    @Bind(R.id.tv_hour)
    TextView mTvHour;
    @Bind(R.id.tv_minute)
    TextView mTvMinute;
    @Bind(R.id.tv_second)
    TextView mTvSecond;
    @Bind(R.id.ll_countTime)
    LinearLayout mLlCountTime;
    @Bind(R.id.ll_count)
    LinearLayout mLlCount;
    @Bind(R.id.imageView)
    ImageView mImageView;
    @Bind(R.id.tv_shop_name)
    TextView mTvShopName;
    @Bind(R.id.tv_attr)
    TextView mTvAttr;
    @Bind(R.id.tv_stockNum)
    TextView mTvStockNum;
    @Bind(R.id.tv_limits)
    TextView mTvLimits;
    @Bind(R.id.tvSub)
    TextView mTvSub;
    @Bind(R.id.etNum)
    EditText mEtNum;
    @Bind(R.id.tvAdd)
    TextView mTvAdd;
    @Bind(R.id.tv_flag)
    TextView mTvFlag;
    @Bind(R.id.tv_edit)
    TextView mTvEdit;
    @Bind(R.id.tv_servicer)
    TextView mTvServicer;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_phone)
    TextView mTvPhone;
    @Bind(R.id.ll_address)
    LinearLayout mLlAddress;
    @Bind(R.id.tv_address)
    TextView mTvAddress;
    @Bind(R.id.tv_self)
    TextView mTvSelf;
    @Bind(R.id.tv_remain_money)
    TextView mTvRemainMoney;
    @Bind(R.id.tv_postage)
    TextView mTvPostage;
    @Bind(R.id.tv_all_money)
    TextView mTvAllMoney;
    @Bind(R.id.tv_hd)
    TextView mTvHd;
    @Bind(R.id.ll_hd)
    LinearLayout mLlHd;
    @Bind(R.id.tv_md)
    TextView mTvMd;
    @Bind(R.id.ll_md)
    LinearLayout mLlMd;
    @Bind(R.id.tv_partner)
    TextView mTvPartner;
    @Bind(R.id.ll_partner)
    LinearLayout mLlPartner;
    @Bind(R.id.iv_weixin)
    ImageView mIvWeixin;
    @Bind(R.id.iv_zhifubao)
    ImageView mIvZhifubao;
    @Bind(R.id.rl)
    RelativeLayout mRl;
    @Bind(R.id.view)
    View mView;
    @Bind(R.id.ll_shopInfo)
    LinearLayout mLlShopInfo;
    @Bind(R.id.ll_bottom)
    LinearLayout mLlBottom;
    private GiftResult mResult;
    private GiftActivity mActivity;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            removeMessages(MESSAGE_WHAT);
            tearDown();
        }
    };
    private String allMoney = "0.00";
    private AlertDialog mDialog;
    private int mPostFlay;
    private String mResponse;
    private String type;
    private Map<String, String> map = new HashMap<>();
    private EventBusMessage message;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private int mFlag;
    private String mOrderid;
    private RefInfo mRefInfo;
    private GiftToPay mGiftToPay;
    List<String> otherIcon = new ArrayList<>();

    private void tearDown() {
        try {
            if (!TextUtils.isEmpty(mActivity.getEtime())) {
                SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date mParse = mFormat.parse(mActivity.getEtime());
                long mRemainTime = (mParse.getTime() - System.currentTimeMillis()) / 1000;
                if (mRemainTime > 0) {
                    mLlCountTime.setVisibility(View.VISIBLE);
                    long mL1 = mRemainTime / 60;  //  分
                    long mL4 = mRemainTime - (mL1 * 60);
                    if (mL4 < 1L) {
                        mTvSecond.setText("00");
                    } else if (mL4 >= 1L && mL4 < 10L) {
                        mTvSecond.setText("0" + mL4);
                    } else {
                        mTvSecond.setText(String.valueOf(mL4));
                    }

                    long mL2 = mL1 / 60;   // 时
                    if (mL2 < 1L) {
                        mTvHour.setText("00");
                    } else if (mL2 >= 1L && mL2 < 10L) {
                        mTvHour.setText("0" + mL2);
                    } else {
                        mTvHour.setText(String.valueOf(mL2));
                    }
                    if (mL1 < 1L) {
                        mTvMinute.setText("00");
                    } else {
                        long mL3 = mL1 - (mL2 * 60);
                        mTvMinute.setText(String.valueOf(mL3));
                    }
                    mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT, 1000);
                } else {
                    mLlCountTime.setVisibility(View.GONE);
                    mTvTimeCountDesc.setText("该活动已结束!");
                }
            } else {
                mLlCountTime.setVisibility(View.GONE);
                mTvTimeCountDesc.setText("该活动已结束!");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_join_group);
        ButterKnife.bind(this);
        mTvTitle.setText("一键开团");
        EventBus.getDefault().register(this);
        if (getIntent() != null) {
            mResult = (GiftResult) getIntent().getSerializableExtra("result");
            mPostFlay = getIntent().getIntExtra("postFlay", 0);
            mResponse = getIntent().getStringExtra("response");
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTimeCountDesc.setText("活动结束倒计时 :");
        if (null != mResult.getActivity() && !"".equals(mResult.getActivity())) {
            mActivity = mResult.getActivity();
            switch (mPostFlay) {
                case 1:   // 邮寄
                    mLlImges.setVisibility(View.VISIBLE);
                    mTvFlag.setText("邮寄收货人信息");
                    mLlAddress.setVisibility(View.VISIBLE);
                    mTvPostage.setVisibility(View.VISIBLE);
                    allMoney = DataUtil.add(mActivity.getAprice(), mActivity.getPostage());
                    break;
                case 2:   // 自提
                    mLlImges.setVisibility(View.GONE);
                    mTvFlag.setText("自提收货人信息");
                    mLlAddress.setVisibility(View.GONE);
                    mTvPostage.setVisibility(View.GONE);
                    allMoney = mActivity.getAprice();
                    break;
            }
            mTvAllMoney.setText(allMoney + "元");
            if (!TextUtils.isEmpty(mActivity.getGattr())) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(mActivity.getGattr());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Iterator<String> keys = jsonObject.keys();
                String attr = "";
                while (keys.hasNext()) {
                    String next = keys.next();
                    String attrValue = jsonObject.optString(next);
                    attr += attrValue + "/";

                }
                mTvAttr.setText("规格: " + attr.substring(0, attr.length() - 1));
            } else {
                mTvAttr.setText("");
            }
            mTvStockNum.setText("库存: " + mActivity.getLaststocknum() + " 件");
            mTvLimits.setText("每人限购 " + mActivity.getLimits() + " 份");
            mTvPostage.setText("快递费: " + mActivity.getPostage() + " 元");

            if (!TextUtils.isEmpty(mActivity.getRedbeanfparticipants())) {
                mLlHd.setVisibility(View.VISIBLE);
                mTvHd.setText("奖 " + mActivity.getRedbeanfparticipants() + " 红豆");
            } else {
                mLlHd.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(mActivity.getInnerfparticipants())) {
                mLlMd.setVisibility(View.VISIBLE);
                mTvMd.setText("奖 " + mActivity.getInnerfparticipants() + " 美豆");
            } else {
                mLlMd.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(mActivity.getCpfparticipants())) {
                mLlPartner.setVisibility(View.VISIBLE);
                mTvPartner.setText("奖 " + mActivity.getCpfparticipants() + " 点合伙人分润权");
            } else {
                mLlPartner.setVisibility(View.GONE);
            }
        }
        mRefInfo = mResult.getRefInfo();
        if (mRefInfo != null && !"".equals(mRefInfo)) {
            Glide.with(UiUtils.getContext()).load(Url.IMG_URL + mRefInfo.getImages())
                    .placeholder(R.mipmap.iv_loading).into(mImageView);
            mTvShopName.setText(mRefInfo.getName());
            mTvSelf.setText("单独购 : " + mRefInfo.getMarketprice() + " 元");
            mTvSelf.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            mTvRemainMoney.setText("立省 " +
                    DataUtil.subtract(mRefInfo.getMarketprice(), mActivity.getAprice()) + " 元");
        }

        GroupInfo mGroupInfo = mResult.getGroupInfo();
        if (mGroupInfo != null && !"".equals(mGroupInfo)) {
            if (!TextUtils.isEmpty(mGroupInfo.getId())) {
                JSONObject mObject = null;
                JSONObject jsonPart = null;
                try {
                    mObject = new JSONObject(mResponse);
                    jsonPart = mObject.optJSONObject("participants");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (null != jsonPart && !"".equals(jsonPart)) {
                    mLlImges.setVisibility(View.VISIBLE);
                    Iterator<String> mKeys = jsonPart.keys();
                    while (mKeys.hasNext()) {
                        String mNext = mKeys.next();
                        String value = jsonPart.optString(mNext);
                        if (mNext.equals(mGroupInfo.getUserid())) {
                            setIcon(value, mIvHead);
                        } else {
                            otherIcon.add(value);
                        }
                    }

                    if (otherIcon.size() == 1) {
                        setIcon(otherIcon.get(0), mIvGroup1);
                    } else if (otherIcon.size() == 2) {
                        setIcon(otherIcon.get(0), mIvGroup1);
                        setIcon(otherIcon.get(1), mIvGroup2);
                    }

                } else {
                    mLlImges.setVisibility(View.GONE);
                }
            } else {
                mLlImges.setVisibility(View.GONE);
            }
        } else {
            mLlImges.setVisibility(View.GONE);
        }

    }

    private void setIcon(String value, ImageView imageView) {
        if (value.startsWith("http://") || value.startsWith("https://")) {
            Glide.with(UiUtils.getContext())
                    .load(value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        } else {
            Glide.with(UiUtils.getContext())
                    .load(Url.BASE_URL + value)
                    .placeholder(R.mipmap.iv_avatar).transform(new GlideCircleTransform(UiUtils.getContext()))
                    .into(imageView);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.removeMessages(MESSAGE_WHAT);
        mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeMessages(MESSAGE_WHAT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventBus(EventBusMessage message) {
        this.message = message;
        if (1 == mPostFlay) {
            mTvName.setText(message.getName());
            mTvPhone.setText(message.getPhone());
            mTvAddress.setText(message.getProvince() + message.getCity() + message.getCountry() + message.getAddress());
        } else {
            mTvName.setText(message.getName());
            mTvPhone.setText(message.getPhone());
        }
    }

    @OnClick({R.id.ivBack, R.id.tvSub, R.id.tvAdd, R.id.tv_edit, R.id.tv_servicer, R.id.iv_weixin, R.id.iv_zhifubao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvSub:
                if (Integer.parseInt(mEtNum.getText().toString().trim()) > 1) {
                    mEtNum.setText(DataUtil.subtract(mEtNum.getText().toString().trim(), "1"));
                    switch (mPostFlay) {
                        case 1:
                            allMoney = DataUtil.add(DataUtil.multiplys(mActivity.getAprice(),
                                    mEtNum.getText().toString().trim(), 2), mActivity.getPostage());
                            break;
                        case 2:
                            allMoney = DataUtil.multiplys(mActivity.getAprice(),
                                    mEtNum.getText().toString().trim(), 2);
                            break;
                    }
                    mTvAllMoney.setText(allMoney + " 元");
                } else {
                    mEtNum.setText("1");
                    ToastUtil.show("至少1件");
                }

                break;
            case R.id.tvAdd:
                if (Integer.parseInt(mEtNum.getText().toString().trim()) < mActivity.getLimits()) {
                    mEtNum.setText(DataUtil.add(mEtNum.getText().toString().trim(), "1"));
                    switch (mPostFlay) {
                        case 1:
                            allMoney = DataUtil.add(DataUtil.multiplys(mActivity.getAprice(),
                                    mEtNum.getText().toString().trim(), 2), mActivity.getPostage());
                            break;
                        case 2:
                            allMoney = DataUtil.multiplys(mActivity.getAprice(),
                                    mEtNum.getText().toString().trim(), 2);
                            break;
                    }
                    mTvAllMoney.setText(allMoney + " 元");
                } else {
                    ToastUtil.show("每人至多" + mActivity.getLimits() + "件");
                }
                break;
            case R.id.tv_edit:
                Intent mIntent = new Intent(this, DialogGiftActivity.class);
                mIntent.putExtra("postFlay", mPostFlay);
                mIntent.putExtra("cert", mResult.getCert());
                startActivity(mIntent);
                break;
            case R.id.tv_servicer:
                popupWindowStoreInfo();
                break;
            case R.id.iv_weixin:

                mFlag = 1;
                if (message != null && !"".equals(message)) {
                    if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                        getOrder();
                    } else {
                        ToastUtil.show("您还没绑定手机,暂无法支付");
                    }
                } else {
                    ToastUtil.show("请先编辑您的相关信息");
                }

                break;
            case R.id.iv_zhifubao:
                mFlag = 2;
                if (message != null && !"".equals(message)) {
                    if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                        getOrder();
                    } else {
                        ToastUtil.show("您还没绑定手机,暂无法支付");
                    }
                } else {
                    ToastUtil.show("请先编辑您的相关信息");
                }
                break;
        }
    }

    private void getOrder() {
        map.clear();
        map.put("cert", mResult.getCert());
        map.put("getermethod", String.valueOf(mPostFlay));
        map.put("goodsnum", mEtNum.getText().toString().trim());
        map.put("username", message.getName());
        map.put("userphone", message.getPhone());
        map.put("authcode", message.getCode());
        if (1 == mPostFlay) {
            map.put("payprice", DataUtil.subtract(allMoney, mActivity.getPostage()));
            map.put("postage", mActivity.getPostage());
            map.put("province", message.getProvince());
            map.put("city", message.getCity());
            map.put("prefecture", message.getCountry());
            map.put("address", message.getAddress());

        } else {
            map.put("payprice", allMoney);
        }
        type = "order";
        getServer(Url.ACTIVITY_GENERATEORDER, map, "", false, null, "post");
    }


    private void popupWindowStoreInfo() {
        mDialog = new AlertDialog.Builder(this, R.style.Translucent_NoTitle).create();
        View view = UiUtils.inflate(R.layout.dialog_gift_shopinfo);
        TextView shopName = (TextView) view.findViewById(R.id.tvShopName);
        TextView tv_tel = (TextView) view.findViewById(R.id.tv_tel);
        TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        TextView tv_address = (TextView) view.findViewById(R.id.tv_address);
        ImageView iv_dimess = (ImageView) view.findViewById(R.id.iv_dimess);
        iv_dimess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        final StoreInfo mStoreInfo = mResult.getStoreInfo();
        shopName.setText(mStoreInfo.getName());
        tv_tel.setText(mStoreInfo.getMphone());
        tv_address.setText(mStoreInfo.getAddress());
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        tv_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mStoreInfo.getMphone())) {
                    mDialog.dismiss();
                    Intent mIntent = new Intent(Intent.ACTION_DIAL);
                    Uri mParse = Uri.parse("tel:" + mStoreInfo.getMphone());
                    mIntent.setData(mParse);
                    startActivity(mIntent);
                } else {
                    ToastUtil.show("暂时无法联系!");
                }
            }
        });
        mDialog.setView(view);
        mDialog.show();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson mGson = new Gson();
        if ("order".equals(type)) {
            GiftOrder mGiftOrder = mGson.fromJson(response, GiftOrder.class);
            MyApplication.getInstance().setSpValue(mGiftOrder.safeobj);
            toPay(mGiftOrder);
        } else if ("topay".equals(type)) {
            try {
                mGiftToPay = mGson.fromJson(response, GiftToPay.class);
                MyApplication.getInstance().setSpValue(mGiftToPay.safeobj);
                mOrderid = mGiftToPay.orderid;
                if (!TextUtils.isEmpty(mGiftToPay.securityKey)) {
                    String mSecurityKey = mGiftToPay.securityKey;
                    String payParams = MyApplication.getInstance().parseSecutiryKey(mSecurityKey);
                    JSONObject jsonObject = new JSONObject(payParams);
                    JSONObject alipay = jsonObject.optJSONObject("alipay");
                    aliPayData = PayAliPayData.parseObject(alipay);
                    JSONObject wechat = jsonObject.optJSONObject("wechat");
                    weixinData = WeixinData.parseObject(wechat);
                    MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "gift").commit();
                    switch (mFlag) {
                        case 1:   //微信支付
                            SpUtils.getInstance().saveSp("orderid", mOrderid);
                            SpUtils.getInstance().saveSp("vc", mGiftToPay.vc);
                            SpUtils.getInstance().saveSp("cert", mGiftToPay.cert);
//                            SpUtils.getInstance().saveSp("id", mActivity.getId());
//                            SpUtils.getInstance().saveSp("sharekey", mResult.getShareKey());
//                            SpUtils.getInstance().saveSp("name", mActivity.getName());
//                            SpUtils.getInstance().saveSp("subject", mActivity.getSubject());
                            SpUtils.getInstance().saveIntSp("userType", mResult.getUserType());
                            SpUtils.getInstance().saveIntSp("num", Integer.parseInt(mEtNum.getText().toString().trim()));
                            weixinPay();  //微信支付
                            break;
                        case 2:   //支付宝支付
                            zhifubaoPay();  //支付宝
                            break;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void toPay(GiftOrder giftOrder) {
        map.clear();
        map.put("orderid", giftOrder.orderid);
        map.put("vc", giftOrder.vc);
        map.put("cert", giftOrder.cert);
        type = "topay";
        getServer(Url.ACTIVITY_TOPAY, map, "", false, null, "post");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson mGson = new Gson();
        BaseResponse mBaseResponse = mGson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
        if (1666 == mBaseResponse.getCode()) {
            ToastUtil.show("服务不可用， 服务器异常");
        } else if (1668 == mBaseResponse.getCode()) {
            ToastUtil.show("支付金额错误");
        } else if (2001 == mBaseResponse.getCode()) {
            ToastUtil.show("库存不足");
        } else if (2002 == mBaseResponse.getCode()) {
            ToastUtil.show("用户购买次数超限");
        }
    }


    private IWXAPI msgApi;
    private PayReq req;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;

    private void weixinPay() {
        msgApi = WXAPIFactory.createWXAPI(UiUtils.getContext(), weixinData.getAppid());
        // 将该app注册到微信
        msgApi.registerApp(weixinData.getAppid());
        getWXOrderInfo();
    }


    /**
     * 获取微信支付订单
     */
    private void getWXOrderInfo() {
        //正常情况下，请求服务器获取订单参数
        req = new PayReq();
        sb = new StringBuffer();
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(JoinGroupActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
            resultunifiedorder = result;
            genPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }

    }

    private void genPayReq() {
        req.appId = weixinData.getAppid();
        req.partnerId = weixinData.getSeller();
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

        Log.e("orion", signParams.toString());

        msgApi.sendReq(req);

    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }


    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            String trade = "";
            if ((mOrderid + genOutTradNo()).length() > 32) {
                trade = (mOrderid + genOutTradNo()).substring(0, 32);
            } else {
                trade = mOrderid + genOutTradNo();
            }
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", weixinData.getAppid()));
            packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId()
                    + "||" + mOrderid + "||4||" + allMoney));
            packageParams.add(new BasicNameValuePair("body", mRefInfo.getName()));
            packageParams.add(new BasicNameValuePair("mch_id", weixinData.getSeller()));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Url.BASE_URL + "/notify/pay/wepay"));  //wepay
            packageParams.add(new BasicNameValuePair("out_trade_no", trade));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", MyApplication.getInstance().getLocalIPAddress()));
            BigDecimal bd = new BigDecimal(allMoney);
            packageParams.add(new BasicNameValuePair("total_fee", bd.multiply(new BigDecimal(100)).intValue() + ""));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");
        } catch (Exception e) {
            return null;
        }
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        return sb.toString();
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（微信）
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }


    private Handler mHandlerpay = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的一部通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        Intent intent = new Intent(UiUtils.getContext(), PaySuccessActivity.class);
                        intent.putExtra("orderid", mOrderid);
                        intent.putExtra("status", 1);
                        intent.putExtra("vc", mGiftToPay.vc);
                        intent.putExtra("cert", mGiftToPay.cert);
                        intent.putExtra("userType", mResult.getUserType());
                        intent.putExtra("num", Integer.parseInt(mEtNum.getText().toString().trim()));
                        startActivity(intent);
                    } else {
                        Intent mIntent = new Intent(UiUtils.getContext(), PaySuccessActivity.class);
                        mIntent.putExtra("orderid", mOrderid);
                        mIntent.putExtra("vc", mGiftToPay.vc);
                        mIntent.putExtra("cert", mGiftToPay.cert);
                        mIntent.putExtra("userType", mResult.getUserType());
                        startActivity(mIntent);
                    }
                    break;
            }
        }
    };

    private void zhifubaoPay() {
        String orderInfo = getOrderInfo(aliPayData);
        //  特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中
        String sign = sign(orderInfo, aliPayData.getRsaPrivate());
        try {
            //仅需对sign做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(JoinGroupActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                mHandlerpay.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    // create the order info. 创建订单信息（支付宝）
    private String getOrderInfo(PayAliPayData alipay) {

        String trade = "";

        if ((mOrderid + genOutTradNo()).length() > 32) {
            trade = (mOrderid + genOutTradNo()).substring(0, 32);
        } else {
            trade = mOrderid + genOutTradNo();
        }

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alipay.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipay.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + trade + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + mRefInfo.getName() + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + getTimeValue() + "||" + MyApplication.getInstance().getUserId()
                + "||" + mOrderid + "||4||" + allMoney + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + allMoney + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + Url.BASE_URL + "/notify/pay/alipay" + "\"";   //api3

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"" + Url.BASE_URL + "\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名（支付宝）
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String rsa_private) {
        return SignUtils.sign(content, rsa_private);
    }

    /**
     * get the sign type we use. 获取签名方式（支付宝）
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    private String getTimeValue() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(date);
        return str;
    }

    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }
}
